var ws = null,
	wo = null;
var scan = null,
	domready = false;
var user_latitude = '';
var user_longitude = '';

var planId = null;
mui.plusReady(function(){

	self = plus.webview.currentWebview();
	planId = self.info.planId;
	
})
// H5 plus事件处理
function plusReady() {
	if(ws || !window.plus || !domready) {
		return;
	}
	// 获取窗口对象
	ws = plus.webview.currentWebview();
	wo = ws.opener();
	// 开始扫描
	ws.addEventListener('show', function() {
		scan = new plus.barcode.Barcode('bcid');
		scan.onmarked = onmarked;
		scan.start({
			conserve: true,
			filename: '_doc/barcode/'
		});
	}, false);
	// 显示页面并关闭等待框
	ws.show('pop-in');
	//wo.evalJS('closeWaiting()');
	
	plus.geolocation.getCurrentPosition(function(res) {
		//成功回调
		user_latitude = res.coords.latitude; //纬度
		user_longitude = res.coords.longitude; //经度
		console.log("经度："+user_longitude+" 纬度："+user_latitude);
	}, function(e) {
		console.log('Gelocation Error: code - ' + e.code + '; message - ' + e.message);
		switch(e.code) {
			case 10:
				mui.alert('请开启应用的定位权限', '提示','确定',function(){},'div');
				break;
			case 9:
				//mui.alert('请开启手机定位服务');
				mui.alert('请开启手机定位服务', '提示','确定',function(){},'div');
				break;
			case 2:
				if(e.message.indexOf("[geolocation:13]") > -1) { 
					//如果网络开启，定位失败，提示检查定位权限
					mui.alert('请开启应用的定位权限', '提示','确定',function(){},'div');
				}
				if(e.message.indexOf("[geolocation:14]") > -1) { 
					//如果应用的权限开了，提示网络异常
					mui.alert('请检查网络是否正常', '提示','确定',function(){},'div');
				}
				break;
			case e.PERMISSION_DENIED:
				mui.alert('请求定位被拒绝', '提示','确定',function(){},'div');
				break;
			case e.POSITION_UNAVAILABLE:
				mui.alert("位置信息不可用", '提示','确定',function(){},'div');
				break;
			case e.TIMEOUT:
				mui.alert("获取位置信息超时", '提示','确定',function(){},'div');
				break;
			case e.UNKNOWN_ERROR:
				mui.alert("未知错误", '提示','确定',function(){},'div');
				break;
		}
	}, {
		//超时未获取到经纬度信息  执行失败回调  (默认为5秒)
		timeout: 3000
	})
}
if(window.plus) {
	plusReady();
} else {
	document.addEventListener('plusready', plusReady, false);
}
// 监听DOMContentLoaded事件
document.addEventListener('DOMContentLoaded', function() {
	domready = true;
	plusReady();
}, false);


var EARTH_RADIUS = 6378.137;    //单位公里
var PI = Math.PI;
function getRad(d){
   return d * Math.PI / 180.0;//经纬度转换成三角函数中度分表形式。
}

/**
 * 计算地球上两点之间的大概距离
 * @param {Object} lat1
 * @param {Object} lng1
 * @param {Object} lat2
 * @param {Object} lng2
 */
function getFlatternDistance(lat1,lng1,lat2,lng2){
    var f = getRad((lat1 + lat2)/2);
    var g = getRad((lat1 - lat2)/2);
    var l = getRad((lng1 - lng2)/2);
    
    var sg = Math.sin(g);
    var sl = Math.sin(l);
    var sf = Math.sin(f);
    
    var s,c,w,r,d,h1,h2;
    var a = EARTH_RADIUS;
    var fl = 1/298.257;
    
    sg = sg*sg;
    sl = sl*sl;
    sf = sf*sf;
    
    s = sg*(1-sl) + (1-sf)*sl;
    c = (1-sg)*(1-sl) + sf*sl;
    
    w = Math.atan(Math.sqrt(s/c));
    r = Math.sqrt(s*c)/w;
    d = 2*w*a;
    h1 = (3*r -1)/2/c;
    h2 = (3*r +1)/2/s;
    
    var distance = d*(1 + fl*(h1*sf*(1-sg) - h2*(1-sf)*sg));
    return distance;
}

//解析URL
/*function getQueryString(url) {
//	var pattern = /(\w+)=(\w+.)/ig;
	var pattern = /([^?&]+)(([^&]*))/ig;
	var parames = {};
	url.replace(pattern, function(a, b, c) {
		parames[b] = c;
	});
	return parames;
}*/

function getQueryString(url) {
  var obj = {}
  var reg = /[?&][^?&]+=[^?&]+/g
  var arr = url.match(reg)
  // ['?id=12345','&a=b']
  if (arr) {
  	arr.forEach(function(item){
      var tempArr = item.substr(1).split('=')
      var key = decodeURIComponent(tempArr[0])
      var val = decodeURIComponent(tempArr[1])
      obj[key] = Number(val);
  	})
    // arr.forEach((item) => {
    //   var tempArr = item.substr(1).split('=')
    //   var key = decodeURIComponent(tempArr[0])
    //   var val = decodeURIComponent(tempArr[1])
    //   obj[key] = Number(val);
    // })
  }
  return obj
}

// 二维码扫描成功
function onmarked(type, result, file) {
	switch(type) {
		case plus.barcode.QR:
			type = 'QR';
			break;
		case plus.barcode.EAN13:
			type = 'EAN13';
			return;
		case plus.barcode.EAN8:
			type = 'EAN8';
			return;
		default:
			type = '其它' + type;
			return;
	}

	var parames = getQueryString(result);
	console.log(JSON.stringify(parames));
	var eqLat = Number(parames['lat']);
	var eqLng = Number(parames['lng']);
	var betweenDis = getFlatternDistance(user_longitude, user_latitude, eqLng, eqLat);
	console.log(betweenDis);
	var userId = localStorage.getItem("userId");
	var taskId = null;
	var flag = false;
	request("/app/alarm/select/task/id/"+parames['siteId']+"/"+userId+"/"+planId, "GET",{
	}, function(res) {
		if(res.code==0){
			taskId = res.result;
			request("/app/alarm/is/point/"+taskId, "GET",{}, function(res) {
				if(res.code==0){
					console.log(flag)
					flag = res.result
					if (betweenDis > 2) {
						mui.alert("请到设备位置再扫码", '提示');
					}
					else if(parames['siteId']) {
						if(flag=="false"){
							openNew("../../html/tour/checkReportDetail.html", {
								siteId: parames['siteId'],
								taskId: taskId
								//siteId: 10
							});
						}
						else{
							openNew("../../html/tour/checkReport.html", {
								siteId: parames['siteId'],
								planId: planId
								//siteId: 10
							});
						}
						// request("/app/alarm/scan/code", "POST",{
						// 	eqId: parames['eqId'],
						// 	systemId: parames['systemId'],
						// 	unitId: parames['unitId'],
						// 	userId: localStorage.getItem("userId")
						// }, function(res) {
						// 	//console.log(res);
						// 	if(res.code==0){
						// 		mui.toast('操作成功');
						// 		mui.back();
						// 	}
						// 	else{
						// 		mui.toast(res.desc);
						// 	}
						// }, true, function() {
						// 	mui.toast("无法识别此二维码")
						// });
						// openNew('../my/userInfo.html', {
						// 	id: parames['playerid']
						// })
					} else {
						alert('无效的二维码！');
						mui.back();
					}
				}
				else {
					alert('请重新扫描！');
					mui.back();
				}
			}, true, function() {

			});
		}
		else{
			alert('请重新扫描！');
			mui.back();
		}
	}, true, function() {

	});
}

//打开外部浏览器
function openUrl(result) {
	var url = getQueryString(result, "url");
	var scene = getQueryString(result, "scene");
	plus.runtime.openURL(url);
}

// 从相册中选择二维码图片 
/*function scanPicture() {
	plus.gallery.pick(function(path) {
		plus.barcode.scan(path, onmarked, function(error) {
			plus.nativeUI.alert('无法识别此图片');
		});
	}, function(err) {
		log('Failed: ' + err.message);
	});
}*/